import 'package:flutter/material.dart';
import 'dart:async';

class BannerWidget extends StatelessWidget {
  BannerWidget({
    Key key,
    this.data,
    this.height = 160.0,
    this.duration = 3,
    this.bannerScrollDirection = Axis.horizontal,
    this.onPageTap,
    this.indicatorNormalColor: Colors.grey,
    this.indicatorNormalSize: 8.0,
    this.indicatorPositioned = const Positioned(
      bottom: 10.0,
    ),
    this.indicatorScaleSize: 1.4,
    this.indicatorScrollDiretion = Axis.horizontal,
    this.indicatorSelectColor: Colors.green,
    this.indicatorSpaceing: 4.0,
  }) : super(key: key);

  // banner子控件
  final List<Widget> data;

  /// banner 高度
  final double height;

  /// 滑动间隔时间
  final int duration;

  /// banner 滑动方向（默认水平）
  final Axis bannerScrollDirection;

  final ValueChanged<int> onPageTap;

  /// 指示器位置
  final Positioned indicatorPositioned;

  /// 指示器方向
  final Axis indicatorScrollDiretion;

  /// 指示器默认颜色
  final Color indicatorNormalColor;

  /// 指示器选中颜色
  final Color indicatorSelectColor;

  /// 指示器大小
  final double indicatorNormalSize;

  /// 指示器选中放大倍数 默认1.4倍
  final double indicatorScaleSize;

  /// 指示器点的间距
  final double indicatorSpaceing;

  Timer _timer;

  final PageController _controller = PageController(initialPage: 200);

  int _getReallyDataSize() {
    return data != null ? data.length : 0;
  }

  /// 有触摸的时候，清空timer
  _resetTimer() {
    if (_timer != null) {
      _timer = null;
      _timer.cancel();
    }

    _timer = new Timer.periodic(Duration(seconds: duration), (timer) {
      if (_controller.page != 0) {
        var nextPageIndex = _controller.page.toInt() + 1;
        _toPage(nextPageIndex);
      }
    });
  }

  void _toPage(int page) {
    _controller.animateToPage(page,
        duration: Duration(milliseconds: 300), curve: Curves.linear);
  }

  @override
  Widget build(BuildContext context) {
    _resetTimer();
    return Container(
      child: SizedBox(
        height: height,
        child: GestureDetector(
          onTapDown: (details) {
            _resetTimer();
          },
          onTapUp: (details) {
            _resetTimer();
          },
          onTapCancel: () {
            _resetTimer();
          },
          onTap: () {
            _resetTimer();
          },
          child: Stack(
            children: <Widget>[
              PageView.builder(
                scrollDirection: bannerScrollDirection,
                controller: _controller,
                itemBuilder: (context, index) {
                  return data[index % _getReallyDataSize()];
                },
                onPageChanged: (index) {
                  _toPage(index);
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}
